package cn.rengy.web.excelsearch;

import cn.rengy.tool.core.IdGenerator;
import cn.rengy.isql.Dao;
import cn.rengy.isql.DbService;
import cn.rengy.isql.NamedSqlDao;
import com.alibaba.excel.util.StringUtils;
import org.apache.commons.collections.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class ExcelSearchService {


    @Autowired
    private Dao dao;
    @Autowired
    private NamedSqlDao namedSqlDao;
    @Autowired
    private DbService dbService;


    public void initMapping(Long taskId) throws IOException {
        dao.update("delete from excel_data2 where task_id=?",taskId);
        //查询所有主表
        List<Map<String,Object>> list=dao.queryForList("select * from excel_data1 where task_id=?",taskId);
        for(Map<String,Object> d:list){
            String key= MapUtils.getString(d,"b");
            Long mapId=MapUtils.getLong(d,"Id");
            if(StringUtils.isNotBlank(key)){
                List<String> textList=FenCi.segment(key);
                String sql="select task_id,_id Id3,a,b from excel_data3 where task_id="+taskId+" and (";
                String sql2="";
                for(String k:textList){
                    if(sql2.length()>0){
                        sql2+=" or ";
                    }
                    sql2+=" a like '%"+k+"%' ";
                }
                String sql3=sql+sql2+")";
                List<Map<String,Object>> list2=dao.queryForList(sql3);
                for(Map<String,Object> m:list2){
                    m.put("Id", IdGenerator.nextId());
                    m.put("mapId", mapId);
                    dbService.updateMapParameter("insert_excel_data2",m);

                }
            }

        }
    }
    @Transactional(rollbackFor = Exception.class)
    public void importSubTable(Long taskId){
        //先删除
        dao.update("delete from excel_data3 where task_id=?",taskId);
        //导入
        File dir=new File("D:\\继远\\经研院\\2024.8.30之前统计\\2021批复");
        listFile(taskId,dir);


    }

    private void listFile(Long taskId,File dir){
        File files [] =dir.listFiles();
        for(File f:files){
            if(f.isDirectory()){
                listFile(taskId,f);
            }else{
                Map<String,Object> param=new HashMap<>();
                param.put("taskId",taskId);
                param.put("Id", IdGenerator.nextId());
                param.put("a", f.getName());
                param.put("b", f.getAbsolutePath());
                dbService.updateMapParameter("insert_excel_data3",param);
            }
        }
    }

}
